package indi.wshape1.takeawaydeliveryinfo.dao.impl;

import indi.wshape1.takeawaydeliveryinfo.dao.BlockDAO;
import indi.wshape1.takeawaydeliveryinfo.domain.Block;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Wshape1
 * @create 2022-11-11 20:21
 */

public class BlockDAOImpl extends BaseDAOImpl<Block> implements BlockDAO {

    @Override
    public Block getByName(String name) {
        List<Block> blocks = executeQuery("SELECT `bl_name`, `info` FROM `block` WHERE `bl_name` = ? LIMIT 1", name);
        if (blocks.size() > 0)
            return blocks.get(0);
        return null;
    }

    @Override
    public void add(Block block) {
        try {
            executeUpdate("INSERT INTO `block`(`bl_name`, `info`) VALUES (?, ?)", block.getName(), block.getInfo());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delByName(String name) throws SQLException {
        executeUpdate("DELETE FROM `block` WHERE `bl_name` = ?", name);
    }

    @Override
    public void update(Block block, String oldName) throws SQLException {
        executeUpdate("UPDATE `block` SET `bl_name` = ?, `info` = ? WHERE `bl_name` = ?",
                block.getName(),
                block.getInfo(),
                oldName
        );
    }

    @Override
    public List<Block> getList() {
        return executeQuery("SELECT `bl_name`, `info` FROM `block`");
    }

    @Override
    public List<Block> getListByPage(int page) {
        return executeQuery("SELECT `bl_name`, `info` FROM `block` LIMIT ?, ?",
                (page - 1) * countPerPage,
                countPerPage
        );
    }

    @Override
    public List<Block> getListByKeywordAndPage(String keyword, int page) {
        return executeQuery("SELECT `bl_name`, `info` FROM `block` WHERE `bl_name` LIKE ? or `info` LIKE ? LIMIT ?, ?",
                "%" + keyword + "%",
                "%" + keyword + "%",
                (page - 1) * countPerPage,
                countPerPage
        );
    }

    @Override
    public List<Block> getListByKeyword(String keyword) {
        return executeQuery("SELECT `bl_name`, `info` FROM `block` WHERE `bl_name` LIKE ? or `info` LIKE ?",
                "%" + keyword + "%",
                "%" + keyword + "%"
        );
    }

    @Override
    public int getCount() {
        return ((Long) executeComplexQuery("SELECT COUNT(*) FROM `block`")[0]).intValue();
    }

    @Override
    public int getCountByKeyword(String keyword) {
        return ((Long) executeComplexQuery(
                "SELECT COUNT(*) FROM `block` WHERE `bl_name` LIKE ? or `info` LIKE ?",
                "%" + keyword + "%",
                "%" + keyword + "%"
        )[0]).intValue();
    }
}
